import json

import requests
import time
import hashlib
import base64
""" 
  人脸特征分析表情WebAPI接口调用示例接口文档(必看)：https://doc.xfyun.cn/rest_api/%E4%BA%BA%E8%84%B8%E7%89%B9%E5%BE%81%E5%88%86%E6%9E%90-%E8%A1%A8%E6%83%85.html
  图片属性：png、jpg、jpeg、bmp、tif图片大小不超过800k
  (Very Important)创建完webapi应用添加服务之后一定要设置ip白名单，找到控制台--我的应用--设置ip白名单，如何设置参考：http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=41891
  错误码链接：https://www.xfyun.cn/document/error-code (code返回错误码时必看)
  @author iflytek
"""
# ImageName = "jingkong.jpg"
# FilePath = "jingkong.jpg"  # 本地图片路径


class FacialExpressionAnalyze:
    def __init__(self):
        self.URL = "http://tupapi.xfyun.cn/v1/expression"
        self.APPID = "eea17ed0"
        self.API_KEY = "aa577a6286b1e50df1eaeb3a1eb67613"
        self.label_map = {
            0: "其他",
            1: "其他表情",
            2: "喜悦",
            3: "愤怒",
            4: "悲伤",
            5: "惊恐",
            6: "厌恶",
            7: "中性"
        }

    def getHeader(self, image_name):
        curTime = str(int(time.time()))
        param = f'{{"image_name":"{image_name}"}}'
        paramBase64 = base64.b64encode(param.encode('utf-8')).decode('utf-8')
        checkSum = hashlib.md5((self.API_KEY + curTime + paramBase64).encode('utf-8')).hexdigest()

        header = {
            'X-CurTime': curTime,
            'X-Param': paramBase64,
            'X-Appid': self.APPID,
            'X-CheckSum': checkSum,
            'Content-Type': 'application/octet-stream'
        }
        return header

    def getBody(self, filePath):
        with open(filePath, 'rb') as f:
            return f.read()

    def getExpression(self, ImageName, FilePath):
        # 发送 POST 请求
        r = requests.post(self.URL, headers=self.getHeader(ImageName), data=self.getBody(FilePath))
        print(r.content.decode('utf-8'))

        response = json.loads(r.content)
        file_info = response['data']['fileList'][0]
        label = file_info['label']
        rate = file_info['rate']
        review = file_info['review'] # False-可信度高， True-可信度低
        # 只有review为false
        print(f"识别表情 label = {label}, 表情为{self.label_map.get(label)}, 置信度 = {rate:.2%}")

        # if review == False:
        return self.label_map.get(label)
